import axios from "axios";
import { showToast } from "vant";

const timeout = 10 * 1000;

const request = axios.create({
  baseURL: "http://121.89.205.189:3000/",
  timeout,
});

interface IErrorMessages {
  [prop: string]: string;
}

const errorMessages: IErrorMessages = {
  [`timeout of ${timeout}ms exceeded`]: "接口超时",
  "Request failed with status code 404": "接口飞了，请再看看",
};

// 请求拦截
request.interceptors.request.use(
  (config) => {
    // 1. 获取token
    const { token } = JSON.parse(localStorage.getItem("user") || "{}");
    // 2. 判断token存在就写入到 config 的 headers 中
    if (token) {
      (config.headers as any).token = token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
request.interceptors.response.use(
  (response) => {
    // 2xx 进入
    const { data } = response;

    // 判断业务状态码是否为 '200'
    if (data.code === "200") {
      return data;
    } else {
      showToast({ message: data.message, position: "top" });

      throw new Error(data.message);
    }
  },
  (error) => {
    // 2xx 之外的进入
    showToast({
      message: errorMessages[error.message] || "网络异常，请稍后重试",
      position: "top",
    });
    return Promise.reject(error);
  }
);

export default request;

// interface IData {
//   a: string;
//   b: string;
//   [propname: string]: string;
// }

// const data: IData = {
//   a: '1',
//   b: '2',
// };
// const key = "f";

// data[key];
